<?php

	class source
	{

		var $fw		= null;
		var $sec	= null;

		function source(&$framework, &$security)
		{

			$this->fw	= &$framework;
			$this->sec	= &$security;

			switch($this->fw->do)
			{

				// called via a ajax command. updates the vote for movie/member
				case 'ajax_vote':
					$this->vote();
					break;

				// process a comment
				case 'comment':
					$this->process_comment();
					break;

				case 'random':
					$this->show_random_movie();
					break;

				case 'browse':
					$this->show_genre_movies();
					break;

				case 'process':
					$this->process_movie_form();
					break;
					
				case 'details':
					$this->show_movie_member_details();
					break;

				case 'view':
					$this->show_movie_details();
					break;

				// =---------------------------------------------=
				// Update

				case 'update':
					$this->process_update_movie();
					break;

				// =---------------------------------------------=
				// Add a movie into the database
				case 'search_results':
					// Returns a list of movies found for ajax
					$this->get_search_results();
					break;

				case 'add':
					$this->show_imdb_search_results();
					break;

				case 'process_add':
					$this->process_add();
					break;

				// =---------------------------------------------=

				case 'edit':
					$this->show_movie_form();
					break;

				default:
					// no default defined
					header('location: index.php');
					exit;
					break;

			}

		}

		// get the details of a particular copy of a movie
		function show_movie_member_details()
		{
			$movie_id	= (int)$_GET['id'];
			$member_id	= (int)$_GET['member'];
			
			// make sure the member exists
			$member	= $this->fw->get_member_details($member_id);
			$movie = $this->fw->get_movie_details($movie_id);
			
			$own_id = $this->fw->movie_own($movie_id, $member_id, true);
			
			if($own_id && $member && $movie) {
				$details = $this->fw->get_movie_own_details($own_id);

				// Paper Chain
				$this->fw->pc_item('Browse', 'Browse all the movies currently in your database');
				$this->fw->pc_item('View', 'View a movie in the database');
				$this->fw->pc_item($movie['title'], 'View details about '.$movie['title'], 'index.php?what=movie&do=view&id='.$movie_id);
				$this->fw->pc_item('Details of '. $member['username'].'&#39;s copy', 'title', 'index.php?what=movie&do=details&id='.$movie_id.'&member='.$member_id);
				
				$this->fw->template = 'movie.owners_details.tpl';
				
				$this->fw->content['movie']		= $movie;
				$this->fw->content['member']	= $member;
				$this->fw->content['details']	= $details;
				
			} else {
				// couldn't load the selected details
			}
		}
		
		function process_add()
		{

			$ids	= $_POST['id'];
			$add	= $_POST['add'];

			$ids	= array_unique(!is_array($ids) ? array($ids) : $ids);

			$added	= array();

			$member_id	= $this->sec->dtls['id'];

			// Time to loop though the ids
			foreach($ids as $id=>$title)
			{

				if(preg_match("/tt(?:[\d]){4,}/i", $id))
				{

					// ensure this id does not already exist
					$sql	= $this->fw->_pq("SELECT movie_id FROM movie_movies WHERE movie_imdb = '%s'", $id);
					$result	= mysql_query($sql) or die(mysql_error());

					if(mysql_num_rows($result) == 0)
					{

						$movie_dtls	= $this->fw->obtain_movie_imdb($id);

						if($movie_dtls)
						{

							$image	= array('filename' => null, 'width' => null, 'height' => null);

							if(isset($movie_dtls['image']) && $this->fw->config['save_image'] == 1)
							{

								$image = $this->fw->imdb_save_image($movie_dtls['image'], $id);

							}

							$also_known_as = trim(implode("\n", $movie_dtls['also_known_as']));

							// =----------------------------------------------------=
							// Adding into database

							$sql	= $this->fw->_pq("INSERT INTO #__movies (movie_title, movie_imdb, movie_year, movie_runtime, movie_created, movie_image_name, movie_image_width, movie_image_height, movie_updated, movie_created_by, movie_updated_by, movie_tagline, movie_plot, movie_imdb_rating, movie_also_known_as) VALUES ('%s', '%s', '%s', %s, UNIX_TIMESTAMP(), '%s', '%s', '%s', UNIX_TIMESTAMP(), '%s', '%s', '%s', '%s', '%s', '%s')", $movie_dtls['title'], $id, $movie_dtls['year'], (int)$movie_dtls['runtime'], $image['filename'], $image['width'], $image['height'], $member_id, $member_id, $movie_dtls['tagline'], $movie_dtls['plot'], $movie_dtls['rating'], $also_known_as);
							$result	= mysql_query($sql) or die(mysql_error());

							if($result && $movie_id = mysql_insert_id())
							{

								// movie has been added

								$list[] = $movie_id;
								$added[$movie_id]	= $movie_dtls['title'];

								// Add the acting cast
								if(isset($movie_dtls['cast'])) {
									foreach($movie_dtls['cast'] as $c) {
										if(($act_id = $this->fw->add_cast_member($c['imdb_id'], $c['name'])) !== false) {
											$sql	= $this->fw->_pq("INSERT INTO #__lnk_movie_actors (movie_id, name_id, mc_character_name, mc_credited_as) VALUES (%s, %s, '%s', '%s');", $movie_id, $act_id, $c['character'], $c['name']);
											$result	= mysql_query($sql) or die(mysql_error());
										}
									}
								}

								// Add the directors
								if(isset($movie_dtls['directors'])) {
									foreach($movie_dtls['directors'] as $d) {
										if(($director_id = $this->fw->add_cast_member($d['imdb_id'], $d['name'])) !== false) {
											$sql	= $this->fw->_pq("INSERT INTO #__lnk_movie_directors (movie_id, name_id, md_credited_as) VALUES (%s, %s, NULL);", $movie_id, $director_id);
											$result	= mysql_query($sql) or die(mysql_error());
										}
									}
								}

								// Add the writers
								if(isset($movie_dtls['writers'])) {
									foreach($movie_dtls['writers'] as $w) {
										if(($writer_id = $this->fw->add_cast_member($w['imdb_id'], $w['name'])) !== false) {
											$sql	= $this->fw->_pq("INSERT INTO #__lnk_movie_writers (movie_id, name_id, mw_credited_as, mw_role) VALUES(%s, %s, NULL, '%s')", $movie_id, $writer_id, $w['role']);
											$result	= mysql_query($sql) or die(mysql_error());
										}
									}
								}

								// Add the genres
								if(isset($movie_dtls['genre']) && is_array($movie_dtls['genre'])) {
									foreach($movie_dtls['genre'] as $id=>$genre_title) {
										// Insert genre link
										$sql	= $this->fw->_pq("INSERT INTO #__lnk_movie_genre (movie_id, genre_id) VALUES (%s, %s)", $movie_id, $id);
										$result	= mysql_query($sql) or die(mysql_error());
									}
								}
							}
						}
					} else {
						// This movie already exists
					}
				} else {
					// Invalid IMDB ID
				}
			}

			if(count($added) > 0) {
				// update the genre count
				$this->fw->update_genre_movie_count();
				// has the user specified that they want to wishlist/collect the added movies?
				if(!empty($add)) {
					unset($_SESSION['id']);
					$_SESSION['id']	= $list;
					header('location: index.php?what='. $add .'&do=add');
					exit;
				} else {
					
					if(count($added) == 1) {
						$_SESSION['msg']	= current($added) . ' was successfully added.';
					} else {
						$_SESSION['msg']	= 'Successfully added the following movies to the database:<br />';
						foreach($added as $title) $_SESSION['msg'] .= $title .'<br />';
					}
				}
			}
			header('location: index.php');
			exit;
		}

		function process_comment()
		{

			$movie_id	= (int)$_POST['movie_id'];
			$comment	= $_POST['comment'];

			$member_id	= (int)$this->sec->dtls['id'];

			// Error checking
			$err = array();

			if(empty($comment))
			{

				$err['comment'] = 'Field can not be blank';

			}
			elseif(strlen($comment) > 2000)
			{

				$err['comment'] = 'Comment has exceeded 2000 characters';

			}

			if(count($err) == 0)
			{

				// saving time!
				$this->fw->save_comment($movie_id, $member_id, $comment);

				$_SESSION['msg'] = 'Comment Successfully Added';
				header('location: index.php?what=movie&do=view&id='. $movie_id .'#comments');
				exit;

			}
			else
			{

				$this->show_movie_details($movie_id);

			}

		}

		function process_movie_form()
		{

			set_time_limit(0);

			$action	= $_POST['action'];
			$id		= $_POST['id'];

			$title	= $_POST['title'];
			$imdb	= $_POST['imdb'];

			$movie_dtls	= $this->fw->obtain_movie_imdb($imdb);

			// Time for some error checking
			$err = array();


			if(empty($title))
			{

				$err['title']	= 'A title must be provided.';

			}
			elseif(strlen($title) > 128)
			{

				$err['title']	= 'Title can not exceed 128 characters.';

			}

			if(!$movie_dtls)
			{

				$err['imdb']	= 'URL is not valid, or not accessable';

			}

			if(count($err) == 0)
			{

				// Extract IMDB id from url

				$preg	= str_replace('/', '\/', str_replace('.', '\.', $this->fw->config['imdb_url']));
				$preg	= str_replace('%%', "(tt[\d]+)", $preg);
				$preg	= "/". $preg ."/";

				if(preg_match($preg, $imdb, $matches))
				{

					$imdb_id	= $matches[1];

					// Lets make sure this movie doesnt already exist
					$sql	= $this->fw->_pq("SELECT COUNT(movie_id) FROM #__movies WHERE movie_id != '%s' AND LOWER(movie_title) = '%s'", $id, strtolower($title));
					$result	= mysql_query($sql) or die(mysql_error());

					if(mysql_result($result, 0, 0) == 0)
					{

						// Time to edit database
						if($action == 'edit')
						{
						}
						else
						{

							// =----------------------------------------------------=
							// Adding into database
							$sql	= $this->fw->_pq("INSERT INTO #__movies (movie_title, movie_imdb, movie_created) VALUES ('%s', '%s', UNIX_TIMESTAMP())", $title, $imdb_id);
							$result	= mysql_query($sql) or die(mysql_error());

							if($result && $movie_id = mysql_insert_id())
							{

								// Record has been created. Save genres
								if(isset($movie_dtls['genre']) && is_array($movie_dtls['genre']))
								{

									foreach($movie_dtls['genre'] as $id=>$genre_title)
									{

										// Insert genre link
										$sql	= $this->fw->_pq("INSERT INTO #__lnk_movie_genre (movie_id, genre_id) VALUES (%s, %s)", $movie_id, $id);
										$result	= mysql_query($sql) or die(mysql_error());

									}

								}


							}

							$_SESSION['msg']	= '\''. stripslashes($title) .'\' successfully added to movie database.';
							header('location: index.php');
							exit;

							// =----------------------------------------------------=

						}

					}
					else
					{

						$this->show_movie_form('The movie title provided already exists.');

					}

				}
				else
				{

					$this->show_movie_form('An error has been found', array('imdb' => 'Unable to extact the imdb from the provided url.'));

				}

			}
			else
			{

				// Error with submitted data
				$this->show_movie_form('An error has been found', $err);

			}

		}

		function process_update_movie()
		{

			// Update the selected movies details from IMDB
			$id	= (int)$_REQUEST['id'];
			if($this->fw->update_movie($id)) {
				$_SESSION['msg']	= 'Movie Successfully Updated';
			} else {
				$_SESSION['msg']	= 'Couldn\'t Update movie';
			}
			header('location: index.php?what=movie&do=view&id='. $id);
			exit;

		}

		function show_genre_movies()
		{

			$genre_id	= $_REQUEST['id'];

			$sql	= $this->fw->_pq("SELECT genre_name FROM #__genre WHERE genre_id = '%s'", $genre_id);
			$result	= mysql_query($sql) or die(mysql_error());

			if(mysql_num_rows($result) === 1)
			{

				$genre_name	= mysql_result($result, 0, 0);

				// Paper Chain
				$this->fw->pc_item('Browse', 'Browse all the movies currently in your database');
				$this->fw->pc_item($genre_name, 'Browse all entries under the '. $genre_name .' category', 'index.php?what=movie&do=browse&id='. $genre_id);

				// Set Smarty Template
				$this->fw->template	= 'movie.browse_genre.tpl';

				$filter	= @$_REQUEST['filter'];
				$search	= @$_REQUEST['search'];

				// paginiation
				$num	= $this->fw->get_count_movies_in_genre($genre_id, $filter, $search);
				$pagin	= $this->fw->pagination($num);

				// Smarty Data
				$this->fw->content['genre_name']	= $genre_name;
				$this->fw->content['genre_id']		= $genre_id;
				$this->fw->content['movies']		= $this->fw->get_genre_movies($genre_id, $filter, $search, $pagin);
				$this->fw->content['pagination']	= $pagin;

				$this->fw->content['alpha_base']	= 'index.php?what=movie&do=browse&id='. $genre_id;

				$this->fw->content['filter']		= $filter;
				$this->fw->content['search']		= $search;

			}
			else
			{

				header('location: index.php');
				exit;

			}

		}

		function show_movie_details($id = null) {

			$id	= ($id !== null) ? $id : (int)$_REQUEST['id'];

			$movie	= $this->fw->get_movie_details($id, true, true, true);

			// ensure the movie exists
			if($movie)
			{

				// setting this movie id as _CUR_MOVIE allows other functions
				// within the program to know we are viewing particular movie
				// effects such things as random movie
				define('_CUR_MOVIE', $id);

				// View count time for this movie (in minutes)
				// stops flooding of the view counter
				$flood_time	= 15;

				// paper chain items
				$this->fw->pc_item('Browse', 'Browse all the movies currently in your database');
				$this->fw->pc_item('View', 'View a movie in the database');
				$this->fw->pc_item($movie['title'], 'View details about '. $movie['title'], 'index.php?what=movie&do=view&id='. $id);

				// call our additional js files
				$this->fw->js[]	= 'ajax.js';
				$this->fw->js[]	= 'movies.view.js';

				// check if a flood timer has been set for this movie or if the flood timer has expired
				if(!isset($_SESSION['view'][$id]) || $_SESSION['view'][$id] + ($flood_time * 60) < time())
				{

					$sql	= $this->fw->_pq("UPDATE #__movies SET movie_views = movie_views + 1 WHERE movie_id = '%s'", $id);
					$result	= mysql_query($sql) or die(mysql_query());
					$_SESSION['view'][$id]	= time();

					// Trim the array. Lets not it get too big to save server resources
					// basically this removes the elements from the beginning of the array
					while(count($_SESSION['view']) > 10)
					{

						// Can not use array_shift as it screws up the keys!
						reset($_SESSION['view']);
						unset($_SESSION['view'][key($_SESSION['view'])]);


					}

				}

				// build the page
				$this->fw->template		= 'movie.view.tpl';

				$image_path				= _BASE_PATH . $this->fw->config['directory_imdb_image'] . $movie['image_name'];

				// Assign Data
				$this->fw->content['movie']		= $movie;
				$this->fw->content['owners']	= $this->fw->get_movie_owned_by($id);
				$this->fw->content['image']		= ($this->fw->config['show_image'] == 1 && !empty($movie['image_name']) && file_exists($image_path)) ? true : false;

				$this->fw->content['own']		= $this->fw->movie_own_details($id, $this->sec->dtls['id']);
				$this->fw->content['wishlist']	= $this->fw->movie_wishlist($id, $this->sec->dtls['id']);

				// get our comments
				if($this->fw->config['comments'] == 1) {
					$this->fw->content['comments'] = $this->fw->get_movie_comments($id);
				}
			} else {
				// No movie returned
			}

		}

		function show_imdb_search_results()
		{

			$this->fw->pc_item('Add movie/s to database', 'Search movies available in IMDB to add to your database');

			$title	= $_REQUEST['title'];
			$this->fw->js[] = 'ajax.js';
			$this->fw->js[] = 'movie.import.js';

			$this->fw->template				= 'movie.imdb_results.tpl';

			$this->fw->content['title']		= $title;

			//$results						= $this->fw->imdb_search_movie_title($title);
			//$this->fw->content['results']	= $results;

		}

		function show_movie_form()
		{

			$this->fw->pc_item('Add To My Collection', 'Add the selected movies from the database to your collection');

			// This function will search imdb for titles.... and list them for the user to choose to add one
			$title	= $_REQUEST['title'];

			$results	= $this->fw->imdb_search_movie_title($title);

			$do		= $this->fw->do;
			$action	= (isset($_REQUEST['action'])) ? $_REQUEST['action'] : $do;
			$id		= @$_REQUEST['id'];

			if($do == 'process')
			{
			}
			else
			{

				if($action == 'edit')
				{
				}
				else
				{

					$title	= ucwords(@$_REQUEST['title']);
					$imdb	= 'http://';

				}

			}

			// Set Smarty Template

			$this->fw->template					= 'movie.form.tpl';
			$this->fw->content['page_title']	= $action == 'edit' ? 'Edit Movie' : 'Add Movie';

			// Form Data
			$this->fw->content['action']		= $action;
			$this->fw->content['id']			= $id;

			$this->fw->content['title']			= $title;
			$this->fw->content['imdb']			= $imdb;
		}

		// search imdb for movie title, return as ajax friendly output
		function get_search_results()
		{
			$this->fw->main_template = null; // turns off smarty (ajax output)
			$title = @$_REQUEST['title'];

			if(!empty($title)) {
				$results = $this->fw->imdb_search_movie_title($title);
				if($results) {
					for($i = 0; $i < count($results); $i++) {
						$v = $results[$i];
						echo implode('|', $v);
						if($i + 1 < count($results)) echo "\n";
					}
				}
			}
		}

		function show_random_movie()
		{

			$movie = $this->fw->get_movie_random();

			header('location: index.php?what=movie&do=view&id='. $movie['id']);
			exit;

		}

		// process a vote for the selected movie/member. if vote already exists updates existing vote =--
		function vote()
		{

			$movie_id	= (int)$_GET['movie'];
			$member_id	= (int)$this->sec->dtls['id'];
			$vote		= (int)$_GET['vote'];

			// because this is used via ajax, if anything fails, we exit. this returns empty to js which it can use.

			// Make sure our vote is valid
			if($vote >= 1 && $vote <= 10)
			{

				// Check if we already have a vote
				$sql	= $this->fw->_pq("SELECT rating_id FROM #__ratings WHERE movie_id = %s AND member_id = %s", $movie_id, $member_id);
				$result	= mysql_query($sql) or die(mysql_error());

				if($row = mysql_fetch_assoc($result))
				{

					// Previous record exists... delete it
					$sql	= $this->fw->_pq("DELETE FROM #__ratings WHERE movie_id = %s AND member_id = %s", $movie_id, $member_id);
					$result	= mysql_query($sql) or die(mysql_error()); // In the event there is duplicate votes from the same member, deleting all records for this movie/member will fix the problem

				}

				// no records currently exist for this movie/member, lets create one!
				$sql	= $this->fw->_pq("INSERT INTO #__ratings (movie_id, member_id, rating_value) VALUES(%s, %s, %s);", $movie_id, $member_id, $vote);
				$result	= mysql_query($sql) or die(mysql_error());

				// update the movie record to reflect these changes
				$stats				= $this->fw->update_movie_ratings($movie_id, true);
				$stats['min_votes'] = $this->fw->config['ratings_min_votes'];

				// Assign our stats back to the content var, and display the ajax template!
				$this->fw->main_template = 'movie.ajax.vote_results.tpl';

				$this->fw->content = $stats;

			}
			else
			{

				// invalid vote!
				exit;

			}

		}

	}

?>
